import {Component, forwardRef, Input, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {NzSizeLDSType} from 'ng-zorro-antd';
import {HttpService} from '../http-interceptors/http-service.';

@Component({
  selector: 'app-select',
  templateUrl: './app-select.component.html',
  styleUrls: ['./app-select.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => AppSelectComponent),
      multi: true
    }]
})
export class AppSelectComponent implements ControlValueAccessor, OnInit {
  deftVal;
  isLoading = false;
  @Input() url: string;
  @Input() nzSize: NzSizeLDSType;
  @Input() method: string;
  @Input() parameter: { key: string; value: any };
  @Input() key: string;
  @Input() name: any;

  listOfOption: Array<{ label: string; value: string }> = [];

  constructor(private http: HttpService) {
  }

  ngOnInit(): void {
    this.isLoading = true;
    if (this.method.startsWith('POST')) {
      this.http.post(this.url, this.parameter).subscribe(value => {
        this.resultHandle(value);
      });
    } else {
      this.http.get(this.url).subscribe(value => {
        this.resultHandle(value);
      });
    }
    this.isLoading = false;
  }

  writeValue(obj: any): void {
    this.deftVal = obj;
  }

  registerOnChange(fn: any): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {
  }

  setDisabledState?(isDisabled: boolean): void {
  }
  isNotSelected(value: string): boolean {
    return this.deftVal.indexOf(value) === -1;
  }
  private resultHandle(value: any) {
    const children: Array<{ label: string; value: string }> = [];
    value.map((currentValue) => {
      children.push({label: currentValue[this.name], value: currentValue[this.key]});
    });
    this.listOfOption = children;
  }

  _onChange(obj: any) {
  }
}
